<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
<!-- threads-basics.qdoc -->
  <title>Threading Basics | Qt 5.14</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td ><a href="index.html">Qt 5.14</a></td><td >Threading Basics</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.14.2 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
  <link rel="start" href="index.html" />
<p class="naviNextPrevious headerNavi">
</p><p/>
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#what-are-threads">What Are Threads?</a></li>
<li class="level2"><a href="#gui-thread-and-worker-thread">GUI Thread and Worker Thread</a></li>
<li class="level2"><a href="#simultaneous-access-to-data">Simultaneous Access to Data</a></li>
<li class="level1"><a href="#using-threads">Using Threads</a></li>
<li class="level2"><a href="#when-to-use-alternatives-to-threads">When to Use Alternatives to Threads</a></li>
<li class="level2"><a href="#which-qt-thread-technology-should-you-use">Which Qt Thread Technology Should You Use?</a></li>
<li class="level1"><a href="#qt-thread-basics">Qt Thread Basics</a></li>
<li class="level2"><a href="#qobject-and-threads">QObject and Threads</a></li>
<li class="level2"><a href="#protecting-the-integrity-of-data">Protecting the Integrity of Data</a></li>
<li class="level2"><a href="#dealing-with-asynchronous-execution">Dealing with Asynchronous Execution</a></li>
<li class="level1"><a href="#examples">Examples</a></li>
<li class="level1"><a href="#digging-deeper">Digging Deeper</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Threading Basics</h1>
<span class="subtitle"></span>
<!-- $$$thread-basics.html-description -->
<div class="descr"> <a name="details"></a>
<a name="what-are-threads"></a>
<h2 id="what-are-threads">What Are Threads?</h2>
<p>Threads are about doing things in parallel, just like processes. So how do threads differ from processes? While you are making calculations on a spreadsheet, there may also be a media player running on the same desktop playing your favorite song. Here is an example of two processes working in parallel: one running the spreadsheet program; one running a media player. Multitasking is a well known term for this. A closer look at the media player reveals that there are again things going on in parallel within one single process. While the media player is sending music to the audio driver, the user interface with all its bells and whistles is being constantly updated. This is what threads are for -- concurrency within one single process.</p>
<p>So how is concurrency implemented? Parallel work on single core CPUs is an illusion which is somewhat similar to the illusion of moving images in cinema. For processes, the illusion is produced by interrupting the processor's work on one process after a very short time. Then the processor moves on to the next process. In order to switch between processes, the current program counter is saved and the next processor's program counter is loaded. This is not sufficient because the same needs to be done with registers and certain architecture and OS specific data.</p>
<p>Just as one CPU can power two or more processes, it is also possible to let the CPU run on two different code segments of one single process. When a process starts, it always executes one code segment and therefore the process is said to have one thread. However, the program may decide to start a second thread. Then, two different code sequences are processed simultaneously inside one process. Concurrency is achieved on single core CPUs by repeatedly saving program counters and registers then loading the next thread's program counters and registers. No cooperation from the program is required to cycle between the active threads. A thread may be in any state when the switch to the next thread occurs.</p>
<p>The current trend in CPU design is to have several cores. A typical single-threaded application can make use of only one core. However, a program with multiple threads can be assigned to multiple cores, making things happen in a truly concurrent way. As a result, distributing work to more than one thread can make a program run much faster on multicore CPUs because additional cores can be used.</p>
<a name="gui-thread-and-worker-thread"></a>
<h3 id="gui-thread-and-worker-thread">GUI Thread and Worker Thread</h3>
<p>As mentioned, each program has one thread when it is started. This thread is called the &quot;main thread&quot; (also known as the &quot;GUI thread&quot; in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example <a href="../qtgui/qpixmap.html">QPixmap</a>, don't work in secondary threads. A secondary thread is commonly referred to as a &quot;worker thread&quot; because it is used to offload processing work from the main thread.</p>
<a name="simultaneous-access-to-data"></a>
<h3 id="simultaneous-access-to-data">Simultaneous Access to Data</h3>
<p>Each thread has its own stack, which means each thread has its own call history and local variables. Unlike processes, threads share the same address space. The following diagram shows how the building blocks of threads are located in memory. Program counter and registers of inactive threads are typically kept in kernel space. There is a shared copy of the code and a separate stack for each thread.</p>
<p class="centerAlign"><img src="images/threadvisual-example.png" alt="&quot;Thread visualization&quot;" /></p><p>If two threads have a pointer to the same object, it is possible that both threads will access that object at the same time and this can potentially destroy the object's integrity. It's easy to imagine the many things that can go wrong when two methods of the same object are executed simultaneously.</p>
<p>Sometimes it is necessary to access one object from different threads; for example, when objects living in different threads need to communicate. Since threads use the same address space, it is easier and faster for threads to exchange data than it is for processes. Data does not have to be serialized and copied. Passing pointers is possible, but there must be a strict coordination of what thread touches which object. Simultaneous execution of operations on one object must be prevented. There are several ways of achieving this and some of them are described below.</p>
<p>So what can be done safely? All objects created in a thread can be used safely within that thread provided that other threads don't have references to them and objects don't have implicit coupling with other threads. Such implicit coupling may happen when data is shared between instances as with static members, singletons or global data. Familiarize yourself with the concept of <a href="threads-reentrancy.html">thread safe and reentrant</a> classes and functions.</p>
<a name="using-threads"></a>
<h2 id="using-threads">Using Threads</h2>
<p>There are basically two use cases for threads:</p>
<ul>
<li>Make processing faster by making use of multicore processors.</li>
<li>Keep the GUI thread or other time critical threads responsive by offloading long lasting processing or blocking calls to other threads.</li>
</ul>
<a name="when-to-use-alternatives-to-threads"></a>
<h3 id="when-to-use-alternatives-to-threads">When to Use Alternatives to Threads</h3>
<p>Developers need to be very careful with threads. It is easy to start other threads, but very hard to ensure that all shared data remains consistent. Problems are often hard to find because they may only show up once in a while or only on specific hardware configurations. Before creating threads to solve certain problems, possible alternatives should be considered.</p>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th >Alternative</th><th >Comment</th></tr></thead>
<tr valign="top" class="odd"><td ><a href="../qtcore/qeventloop.html#processEvents">QEventLoop::processEvents</a>()</td><td >Calling <a href="../qtcore/qeventloop.html#processEvents">QEventLoop::processEvents</a>() repeatedly during a time-consuming calculation prevents GUI blocking. However, this solution doesn't scale well because the call to processEvents() may occur too often, or not often enough, depending on hardware.</td></tr>
<tr valign="top" class="even"><td ><a href="../qtcore/qtimer.html">QTimer</a></td><td >Background processing can sometimes be done conveniently using a timer to schedule execution of a slot at some point in the future. A timer with an interval of 0 will time out as soon as there are no more events to process.</td></tr>
<tr valign="top" class="odd"><td ><a href="../qtcore/qsocketnotifier.html">QSocketNotifier</a> <a href="../qtnetwork/qnetworkaccessmanager.html">QNetworkAccessManager</a> <a href="../qtcore/qiodevice.html#readyRead">QIODevice::readyRead</a>()</td><td >This is an alternative to having one or multiple threads, each with a blocking read on a slow network connection. As long as the calculation in response to a chunk of network data can be executed quickly, this reactive design is better than synchronous waiting in threads. Reactive design is less error prone and energy efficient than threading. In many cases there are also performance benefits.</td></tr>
</table></div>
<p>In general, it is recommended to only use safe and tested paths and to avoid introducing ad-hoc threading concepts. The <a href="../qtconcurrent/qtconcurrent.html">QtConcurrent</a> module provides an easy interface for distributing work to all of the processor's cores. The threading code is completely hidden in the <a href="../qtconcurrent/qtconcurrent.html">QtConcurrent</a> framework, so you don't have to take care of the details. However, <a href="../qtconcurrent/qtconcurrent.html">QtConcurrent</a> can't be used when communication with the running thread is needed, and it shouldn't be used to handle blocking operations.</p>
<a name="which-qt-thread-technology-should-you-use"></a>
<h3 id="which-qt-thread-technology-should-you-use">Which Qt Thread Technology Should You Use?</h3>
<p>See the <a href="threads-technologies.html">Multithreading Technologies in Qt</a> page for an introduction to the different approaches to multithreading to Qt, and for guidelines on how to choose among them.</p>
<a name="qt-thread-basics"></a>
<h2 id="qt-thread-basics">Qt Thread Basics</h2>
<p>The following sections describe how QObjects interact with threads, how programs can safely access data from multiple threads, and how asynchronous execution produces results without blocking a thread.</p>
<a name="qobject-and-threads"></a>
<h3 id="qobject-and-threads">QObject and Threads</h3>
<p>As mentioned above, developers must always be careful when calling objects' methods from other threads. <a href="../qtcore/qobject.html#thread-affinity">Thread affinity</a> does not change this situation. Qt documentation marks several methods as thread-safe. <a href="../qtcore/qcoreapplication.html#postEvent">postEvent()</a> is a noteworthy example. A thread-safe method may be called from different threads simultaneously.</p>
<p>In cases where there is usually no concurrent access to methods, calling non-thread-safe methods of objects in other threads may work thousands of times before a concurrent access occurs, causing unexpected behavior. Writing test code does not entirely ensure thread correctness, but it is still important. On Linux, Valgrind and Helgrind can help detect threading errors.</p>
<a name="protecting-the-integrity-of-data"></a>
<h3 id="protecting-the-integrity-of-data">Protecting the Integrity of Data</h3>
<p>When writing a multithread application, extra care must be taken to avoid data corruption. See <a href="threads-synchronizing.html">Synchronizing Threads</a> for a discussion on how to use threads safely.</p>
<a name="dealing-with-asynchronous-execution"></a>
<h3 id="dealing-with-asynchronous-execution">Dealing with Asynchronous Execution</h3>
<p>One way to obtain a worker thread's result is by waiting for the thread to terminate. In many cases, however, a blocking wait isn't acceptable. The alternative to a blocking wait are asynchronous result deliveries with either posted events or queued signals and slots. This generates a certain overhead because an operation's result does not appear on the next source line, but in a slot located somewhere else in the source file. Qt developers are used to working with this kind of asynchronous behavior because it is much similar to the kind of event-driven programming used in GUI applications.</p>
<a name="examples"></a>
<h2 id="examples">Examples</h2>
<p>Qt comes with several examples for using threads. See the class references for <a href="../qtcore/qthread.html">QThread</a> and <a href="../qtcore/qthreadpool.html">QThreadPool</a> for simple examples. See the <a href="examples-threadandconcurrent.html">Threading and Concurrent Programming Examples</a> page for more advanced ones.</p>
<a name="digging-deeper"></a>
<h2 id="digging-deeper">Digging Deeper</h2>
<p>Threading is a very complicated subject. Qt offers more classes for threading than we have presented in this tutorial. The following materials can help you go into the subject in more depth:</p>
<ul>
<li>The <a href="threads.html">Thread Support in Qt</a> document is a good starting point into the reference documentation.</li>
<li>Qt comes with several additional examples for <a href="examples-threadandconcurrent.html">QThread and QtConcurrent</a>.</li>
<li>Several good books describe how to work with Qt threads. The most extensive coverage can be found in <i>Advanced Qt Programming</i> by Mark Summerfield, Prentice Hall - roughly 70 of 500 pages cover <a href="../qtcore/qthread.html">QThread</a> and <a href="../qtconcurrent/qtconcurrent.html">QtConcurrent</a>.</li>
</ul>
</div>
<!-- @@@thread-basics.html -->
<p class="naviNextPrevious footerNavi">
</p>
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2020 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br/>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br/>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>
